<?php
/**
 * Customize the public methods.
 */

use Illuminate\Support\Facades\Cache;

if(!function_exists('responseArray')){
    /**
     * Todo:: Unified response returns data.
     * @param string $code
     * @param bool $status
     * @param string $message
     * @param array $data
     * @return array
     */
    function responseArray($code='000000',$status=true,$message='Success',$data=[]){
        return array(
            'code' => $code,
            'status' => $status,
            'message' => $message,
            'data' => $data,
        );
    }
}

if (!function_exists('imageUrl')) {
    /**
     * Todo:: Complete picture address.
     * @param $path
     * @return string
     */
    function imageUrl($path)
    {
        if(empty($path)){
            return false;
        }
        if (!preg_match("/^(http:\/\/|https:\/\/).*$/", $path)) {
            $file  = base_path().'/public/storage/'.$path;
            if(file_exists($file)){
                $storageUrl = asset('storage') . '/' . $path;
                return $storageUrl;
            }
            $file  = base_path().'/public/'.$path;
            if(file_exists($file)){
                $scheme = empty($_SERVER['HTTPS']) ? 'http://' : 'https://';
                $url = $scheme.$_SERVER['HTTP_HOST'].'/'.$path;
                return $url;
            }
        }
        return $path;
    }
}

if (!function_exists('delDirFile')) {
    /**
     * 删除文件夹及文件夹下面的文件 或者 删除文件
     * @param $dir  路径地址 目录或文件地址
     * @param string $isType 属性 array('dir','file')
     * @return bool
     */
    function delDirFile($dir, $isType = 'dir')
    {
        if (!in_array($isType, array('dir', 'file'))) {
            return false;
        }
        if ($isType == 'file') {
            // 删除文件
            if (!file_exists($dir)) {
                // 文件不存在
                return false;
            } else {
                unlink($dir);
                if (!file_exists($dir)) {
                    return true;
                } else {
                    return false;
                }
            }
        } else {
            if (!is_dir($dir)) {
                // 文件目录不存在
                return false;
            }
        }
        $dh = opendir($dir);
        while ($file = readdir($dh)) {
            if ($file != "." && $file != "..") {
                $fullpath = $dir . "/" . $file;
                if (!is_dir($fullpath)) {
                    unlink($fullpath);
                } else {
                    delDirFile($fullpath);
                }
            }
        }
        closedir($dh);
        if (rmdir($dir)) {
            return true;
        } else {
            return false;
        }
    }
}

if (!function_exists('pagingLists')) {
    /**
     * Todo:: laravel 独有分页
     * @param $lists
     * @return array
     */
    function pagingLists($lists){
        return [
            'total' => $lists->total(),
            'current_page' => $lists->currentPage(), // 当前页
            'per_page' => $lists->perPage(), // 每页的数据条数。
            'last_page' => $lists->lastPage(), // 获取最后一页的页码
        ];
    }
}

if (!function_exists('isPermission')) {
    /**
     * Todo:: 判断操作权限
     * @param $address
     * @param string $v
     * @return bool
     */
    function isPermission($address,$v='v1'){
        return \App\Libs\Common\Cache\PermissionMenu::getPermission($v,$address);
    }
}


if (!function_exists('listToTree')) {
    /**
     * 数组转树 -后台菜单
     * @param $list
     * @param int $root
     * @param string $pk
     * @param string $pid
     * @param string $child
     * @return array
     */
    function listToTree($list, $root = 0, $pk = 'id', $pid = 'parent_id', $child = '_child')
    {
        // 创建Tree
        $tree = array();
        if (is_array($list)) {
            // 创建基于主键的数组引用
            $refer = array();
            foreach ($list as $key => $data) {
                $refer[$data[$pk]] = &$list[$key];
            }
            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parentId = 0;
                if (isset($data[$pid])) {
                    $parentId = $data[$pid];
                }
                if ((string)$root == $parentId) {
                    $tree[] = &$list[$key];
                } else {
                    if (isset($refer[$parentId])) {
                        $parent = &$refer[$parentId];
                        $parent[$child][] = &$list[$key];
                    }
                }
            }
        }
        return $tree;
    }
}


if (!function_exists('node_tree')) {
    /**
     *  后台菜单排序
     * @param $arr
     * @param int $id
     * @param int $level
     * @return array
     */
    function nodeTree($arr, $id = 0, $level = 0)
    {
        static $array = array();
        foreach ($arr as $v) {
            if ($v['parent_id'] == $id) {
                $v['level'] = $level;
                $array[] = $v;
                nodeTree($arr, $v['id'], $level + 1);
            }
        }
        return $array;
    }
}

if (!function_exists('arr2str')) {
    /**
     * Todo:: 日志对比
     * @param $arr
     * @param string $str
     * @return string
     */
    function arr2str($arr, $str = '')
    {
        if (is_array($arr)) {
            foreach ($arr as $k => $v) {
                if (is_array($v)) {
                    return arr2str($v, $str);
                } else {
                    $str .= "<p>{$k}-->{$v}</p>";
                }
            }
        }
        return $str;
    }
}

if (!function_exists('cleanUpViewCache')) {
    /**
     * Todo:: 清理视图缓存
     */
    function cleanUpViewCache(){
        $dir =   storage_path() . "/framework/views";
        if(!is_dir($dir)){
            return false;
        }
        $dh = opendir($dir);
        if($dh) {
            while (($file = readdir($dh)) !== false) {
                if ($file != "." && $file != "..") {
                    $fullPath = $dir . "/" . $file;
                    $pathInfo = pathinfo($fullPath);
                    if ($pathInfo['extension'] == 'php') {
                        if (!is_dir($fullPath)) {
                            unlink($fullPath);
                        }
                    }
                }
            }
            closedir($dh);
        }
    }
}

if (!function_exists('cleanUpCache')) {
    /**
     * Todo:: 清除所有缓存
     */
    function cleanUpCache(){
        Cache::flush();
    }
}


if (!function_exists('uploadImage')) {
    /**
     * 上传图片
     * @param $key
     * @param string $dirAddress 存放目录地址
     * @return array|\Illuminate\Http\JsonResponse
     */
    function uploadImage($key, $dirAddress = '')
    {
        // 上传文件目录地址 /storage/app/public
        if (empty($dirAddress)) {
            $dirAddress = "/images/" . date('Y') . "/" . date('m')."/".date('d');
        }
        // 1.检查是否上传文件存在
        if (\request()->hasFile($key)) {
            // 2.获取上传文件信息
            $file = request()->file($key);
            // 3.检查合法性 HTTP上载未发生错误
            if ($file->isValid()) {
                // 4.检查上传文件 后缀(将字符串设为小写)是否在范围之内
                if (in_array(strtolower($file->extension()), array('jpeg', 'jpg', 'gif', 'gpeg', 'png'))) {
                    // 5.将上传文件名 取一个新名称
//                    if(empty($fileName)){
//                        $fileName = 'img_'.time().str_random(7).$file->getClientOriginalName();
//                    }
                    // 6.移动文件
                    // $file->move(base_path().'/storage/app/public/img/',$newName);
                    // 判断上传图片大小
                    $fireSize = $file->getSize()/1024/1024/1024; // KB
                    if($fireSize > 500){
                        // 压缩图片
                        $ImgCompress = new \App\Libs\Common\ImgCompress($file->getPathname());
                        $url = $ImgCompress->ImageSaveAddress();
                    }else{
                        // 本地化 建立目录
                        \Illuminate\Support\Facades\Storage::disk('public')->makeDirectory($dirAddress);
                        //存入本地 获得本地文件地址
                        $url = \Illuminate\Support\Facades\Storage::disk('public')->put($dirAddress, $file);
                    }
                    $src = asset('storage/' . $url);    // 补全地址 http://
                    if ($url) {
                        return array(
                            'code' => '000000',
                            'status' => true,
                            'message' => '上传成功',
                            'data' => ['src'=>$src,'directory'=>$url],
                        );
                    } else {
                        return array(
                            'code' => '120000',
                            'status' => false,
                            'message' => '移动文件失败',
                            'data' => [],
                        );
                    }
                } else {
                    return array(
                        'code' => '120010',
                        'status' => false,
                        'message' => '上传文件后缀不符合',
                        'data' => [],
                    );
                }
            } else {
                return array(
                    'code' => '120020',
                    'status' => false,
                    'message' => '上传文件格式不正确',
                    'data' => [],
                );
            }
        }
        return array(
            'code' => '120030',
            'status' => false,
            'message' => '没有上传文件',
            'data' => [],
        );
    }
}
if (!function_exists('deleteImage')) {
    /**
     * 删除本地上传文件
     * @param $path
     * @return mixed
     */
    function deleteImage($path)
    {
        if (!preg_match("/^(http:\/\/|https:\/\/).*$/", $path)) {
            $status = \Illuminate\Support\Facades\Storage::disk('public')->delete($path);  // 删除上传文件
        }else{
            $status = false;
        }
        return $status;
    }
}

if (!function_exists('arrayToObject')) {
    /**
     * Todo:: 数组 转 对象
     * @param array $arr 数组
     * @return object
     */
    function arrayToObject($arr)
    {
        if (gettype($arr) != 'array') {
            return;
        }
        foreach ($arr as $k => $v) {
            if (gettype($v) == 'array' || getType($v) == 'object') {
                $arr[$k] = (object)arrayToObject($v);
            }
        }
        return (object)$arr;
    }
}

if (!function_exists('objectToArray')) {
    /**
     * Todo:: 对象 转 数组
     * @param object $obj 对象
     * @return array
     */
    function objectToArray($obj)
    {
        $obj = (array)$obj;
        foreach ($obj as $k => $v) {
            if (gettype($v) == 'resource') {
                return;
            }
            if (gettype($v) == 'object' || gettype($v) == 'array') {
                $obj[$k] = (array)objectToArray($v);
            }
        }

        return $obj;
    }
}

if (!function_exists('adminLoginToken')) {
    /**
     * Todo:: 用户访问后台登录token
     * @param $username
     * @return string
     */
    function adminLoginToken($username){
        $key = config('app.admin_key');
        $loginUrl = md5(sha1($username.$key));
        return $loginUrl;
    }
}

if (!function_exists('adminLoginUrl')) {
    /**
     * Todo:: 用户访问后台登录地址
     * @param $username
     * @return string
     */
    function adminLoginUrl($username){
        $token = adminLoginToken($username);
        $url = $_SERVER['SERVER_NAME']."/admin?username={$username}&token={$token}";
        return $url;
    }
}
